package com.mirei.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mirei.dto.UserDTO;
import com.mirei.entity.Role;
import com.mirei.entity.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * @author mirei
 */
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/json;charset=utf-8");

        String username = authentication.getName();
        UserDTO userDTO = (UserDTO)authentication.getPrincipal();
        List<Role> roles = userDTO.getRoles();

        HashMap<String, Object> responseBody = new HashMap<>();
        responseBody.put("status", HttpServletResponse.SC_OK);
        responseBody.put("message", "登录成功");
        responseBody.put("username", username);
        responseBody.put("roles", roles);

        ObjectMapper objectMapper = new ObjectMapper();
        String jsonResponse = objectMapper.writeValueAsString(responseBody);

        response.getWriter().write(jsonResponse);
    }
}
